package com.nx.platform.es.biz.esspider.app;

import com.google.common.base.Stopwatch;
import com.google.common.util.concurrent.Service;
import com.nx.platform.es.biz.esspider.reactor.ImportReactor;
import com.nx.platform.es.biz.esspider.reactor.Reactor;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.core.config.ConfigurationSource;
import org.apache.logging.log4j.core.config.Configurator;

import java.io.FileInputStream;

/**
 * 用于对离线文件进行索引更新
 * @author
 * @date 2018/04/13
 */
public class Importer {
    private final Reactor reactor;
    private final String configFilePath;

    private Importer(String configFilePath, String dataFilePath,
            String configNamespace,
            String targetSinks, String sourceFiles) {
        this.configFilePath = configFilePath;
        this.reactor = ImportReactor.builder()
                .configFilePath(configFilePath)
                .dataFilePath(dataFilePath)
                .configNamespace(configNamespace)
                .targetSinks(targetSinks)
                .sourceFiles(sourceFiles)
                .build();
    }

    public static void run(String configFilePath, String dataFilePath,
            String configNamespace,
            String targetSinks, String sourceFiles)
            throws Exception {
        new Importer(configFilePath, dataFilePath, configNamespace, targetSinks, sourceFiles).run();
    }

    public void run() throws Exception {
        // log4j
        String log4jConf = configFilePath + "/log4j2.xml";
        Configurator.initialize(null, new ConfigurationSource(new FileInputStream(log4jConf)));
        Logger logger = LogManager.getLogger(Importer.class);
        // shutdown hook
        final Stopwatch time = Stopwatch.createStarted();
        Runtime.getRuntime().addShutdownHook(new Thread("ShutdownHook") {
            public void run() {
                logger.info(String.format("=-= %-23s =-=", "run time " + time));
                logger.info(String.format("=-= %-23s =-=", "safty-shutdown starting"));
                if (reactor != null && reactor.state() != Service.State.FAILED) {
                    reactor.stopAsync().awaitTerminated();
                }
                logger.info(String.format("=-= %-23s =-=", "safty-shutdown finished"));
            }
        });
        // run
        try {
            reactor.startAsync().awaitTerminated();
            logger.info("finished!");
            System.exit(0);
        } catch (Throwable e) {
            logger.error("error!", e);
            System.exit(1);
        }

    }

}
